<?php

/**
 * Purify HTML
 *
 * @category Ext
 * @package Ext_Service
 * @subpackage HtmlPurifier
 */
class Ext_Service_HtmlPurifier implements Zend_Filter_Interface
{
    /**
     * @var HTMLPurifier
     */
    protected $_purifier;

    /**
     * @var HTMLPurifier_Config
     */
    protected $_purifierConfig;

    /**
     * @var bool
     */
    protected $_enabled = true;

    public function __construct()
    {
        HTMLPurifier_Bootstrap::registerAutoload();
    }
    
    /**
     * @return bool
     */
    public function isAvailable()
    {
        return Zend_Loader_Autoloader::autoload('HTMLPurifier');
    }

    /**
     * @param string $value
     * @return string Purified
     */
    public function filter($value)
    {
        return $this->purify($value);
    }

    /**
     * @param $html
     * @param null|HTMLPurifier_Config $config
     * @return string Purified
     */
    public function purify(&$html, $config = null)
    {
        if (!$this->getEnabled()) {
            return $html;
        }

        $purifier = $this->getPurifier();
        $purified = $purifier->purify($html, $config);

        return $purified;
    }

    /**
     * @param HTMLPurifier $purifier
     * @return Ext_Service_HtmlPurifier
     */
    public function setPurifier($purifier)
    {
        $this->_purifier = $purifier;

        return $this;
    }

    /**
     * @return \HTMLPurifier
     */
    public function getPurifier()
    {
        if (null === $this->_purifier) {
            $this->_purifier = new HTMLPurifier_Base($this->getPurifierConfig());
        }
        return $this->_purifier;
    }

    /**
     * @param HTMLPurifier_Config $purifierConfig
     * @return Ext_Service_HtmlPurifier
     */
    public function setPurifierConfig($purifierConfig)
    {
        $this->_purifierConfig = $purifierConfig;

        return $this;
    }

    /**
     * @return HTMLPurifier_Config
     */
    public function getPurifierConfig()
    {
        if (null === $this->_purifierConfig) {
            $this->_purifierConfig = $this->loadConfig('default');
        }
        return $this->_purifierConfig;
    }

    /**
     * @param $section
     * @return HTMLPurifier_Config
     */
    public function loadConfig($section)
    {
        return HTMLPurifier_Config::createDefault();
    }

    /**
     * @param boolean $enabled
     * @return Ext_Service_HtmlPurifier
     */
    public function setEnabled($enabled)
    {
        $this->_enabled = $enabled;

        return $this;
    }

    /**
     *
     * @return boolean
     */
    public function getEnabled()
    {
        return $this->_enabled;
    }
}